package com.longshen.dubbo.api.tools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * servlet工具类
 * 
 * @class: ServletTools
 * @title: servlet工具类
 * @desc:
 * @author: shen_antonio
 * @date: Mar 27, 2017 5:20:10 PM
 * @since: 1.0.0
 */
public class ServletTools {

  public static HttpSession getSession(boolean create) {
    HttpSession session = null;
    try {
      session = getRequest().getSession(create);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return session;
  }

  public static HttpServletRequest getRequest() {
    ServletRequestAttributes attrs =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    return attrs.getRequest();
  }

  public static HttpServletResponse getResponse() {
    ServletRequestAttributes attrs =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    return attrs.getResponse();
  }

  public static String getClientIP() {
    HttpServletRequest request = getRequest();
    // String fromSource = "X-Forwarded-For";
    String ip = request.getHeader("X-Forwarded-For");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("X-Real-IP");
      // fromSource = "X-Real-IP";
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
      // fromSource = "Proxy-Client-IP";
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
      // fromSource = "WL-Proxy-Client-IP";
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
      // fromSource = "request.getRemoteAddr";
    }

    // 生产互联网环境中，正常ip链是2个：
    // 1.互联网接入区F5到nginx（X-Forwarded-For:clientip1）
    // 2.nginx到应用服务器（X-Forwarded-For:clientip1）
    // 故不接受超过2个以上的X-Forwarded-For请求，这种情况下的IP不准且不允许
    // 生产办公网环境中，正常ip链是1个：
    // 1.核心业务区F5到应用服务器（X-Forwarded-For:clientip1）
    String clientIP = null;
    if (StringUtils.isNotBlank(ip)) {
      String[] ipArray = ip.split(",");
      if (ipArray != null) {
        if (ipArray.length >= 2) {
          clientIP = ipArray[ipArray.length - 2]; // 取倒数第二个，前面的ip是互联网加的头
        } else
          clientIP = ipArray[0];
      }
    }
    StringUtils.trimToEmpty(clientIP);
    return clientIP;
  }

}
